package fy.erp.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.Element;

import com.seeyon.v3x.webmail.domain.MailInfo;

import fy.config.FyConfig;
import fy.form.listen.set.IFormSetting;
import fy.util.DBUtil;
import fy.util.MyUtil;

public class LingLiaoDao {

	private static Log log = LogFactory.getLog(LingLiaoDao.class);

	/*private static String updateSQL = " update apps.fyg_inv_delv_headers@"
			+ FyConfig.getERP_DB_CONFIG().getDblink()
			+ " f set f.oa_status = ? where f.req_num = ? and f.oa_status <> '已审批'";*/
private static String updateSQL = " update apps.fyg_inv_delv_headers f set f.oa_status = ? where f.req_num = ? and f.oa_status <> '已审批'";
	private static String formTable;

	private static String column;

	private static String queryERPNumberSQL;

	private static void sendMail(String content) {
		MailInfo mi = new MailInfo();
		mi.setTo("erp@fuyaogroup.com");
		mi.setFrom("oasystem@fuyaogroup.com");
		mi.setSubject("领料发料单异常");
		mi.setContentText(content);
		MyUtil.sendMail(mi);
	}

	public static boolean save(String erpNumber, short flowStatus) {
		
		Connection conn = null;
		PreparedStatement pst = null;
		boolean success = false;
System.out.println("*****"+flowStatus+"*****"+IFormSetting.FINISH_STATUS+"*************"+erpNumber);

		try {

			//conn = DBUtil.connect(FyConfig.getOA_DB_CONFIG());
			conn = DBUtil.connect(FyConfig.getERP_DB_CONFIG());
			pst = conn.prepareStatement(updateSQL);
			pst.setString(
					1,
					flowStatus == IFormSetting.FINISH_STATUS ? "已审批"
							: (flowStatus == IFormSetting.START_STATUS ? "已提交"
									: (flowStatus == IFormSetting.STOP_STATUS || flowStatus == IFormSetting.CANCEL_STATUS) ? "已退回"
											: "未知状态"));

			pst.setString(2, erpNumber);

			pst.execute();

			conn.commit();

			success = true;

		} catch (Exception e) {
			e.printStackTrace();
			log.error(
					new StringBuilder().append("存储领料发料单状态异常，ERP单据号:")
							.append(erpNumber).toString(), e);
			if (flowStatus == IFormSetting.FINISH_STATUS
					|| flowStatus == IFormSetting.STOP_STATUS
					|| flowStatus == IFormSetting.CANCEL_STATUS) {
				sendMail("更改领料发料单状态发生异常，ERP单据号："
						+ erpNumber
						+ "，状态："
						+ (flowStatus == IFormSetting.FINISH_STATUS ? "已审批"
								: (flowStatus == IFormSetting.START_STATUS ? "已提交"
										: (flowStatus == IFormSetting.STOP_STATUS || flowStatus == IFormSetting.CANCEL_STATUS) ? "已退回"
												: "未知状态")));
			}
		} finally {
			DBUtil.close(pst, conn);
		}

		return success;
	}

	public static String queryERPNumber(long summaryID) {
		String erpNumber = null;
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;

		try {
			conn = DBUtil.connect(FyConfig.getOA_DB_CONFIG());

			if (formTable == null || column == null) {
				pst = conn
						.prepareStatement("select a.datadefine from col_summary s,form_appmain a where s.form_appid = a.id and s.id = ?");

				pst.setLong(1, summaryID);

				rs = pst.executeQuery();

				if (rs.next()) {
					String datadefine = rs.getString(1);
					parseDataDefine(datadefine);
					queryERPNumberSQL = new StringBuilder()
							.append(" select f.")
							.append(column)
							.append(" from col_summary s ,")
							.append(formTable)
							.append(" f where s.id = ? and s.form_recordid = f.id")
							.toString();
				}
				DBUtil.close(rs, pst);
			}

			pst = conn.prepareStatement(queryERPNumberSQL);
			pst.setLong(1, summaryID);
			rs = pst.executeQuery();

			if (rs.next()) {
				erpNumber = rs.getString(1);
			}

		} catch (Exception e) {
			e.printStackTrace();
			log.error("表单撤销事件查询ＥＲＰ单据编号发生异常,单据号：" + summaryID, e);
		} finally {
			DBUtil.close(rs, pst, conn);
		}

		return erpNumber;
	}

	private static void parseDataDefine(String datadefine) throws Exception {
		Document doc = org.dom4j.DocumentHelper.parseText(datadefine);

		Element root = doc.getRootElement();

		List nodes = root.selectNodes("//Define/DataDefine/TableList/Table");

		if (nodes != null) {
			for (Iterator iter = nodes.iterator(); iter.hasNext();) {
				Element node = (Element) iter.next();
				String name = node.attributeValue("name");
				if (name.indexOf("formmain") != -1) {
					formTable = name;
				}
			}
		}

		nodes.clear();
		nodes = root
				.selectNodes("//Define/DataDefine/TableList/Table/FieldList/Field");

		if (nodes != null) {
			for (Iterator iter = nodes.iterator(); iter.hasNext();) {
				Element node = (Element) iter.next();
				String display = node.attributeValue("display");
				if (display.equals("ERP单据编号")) {
					column = node.attributeValue("name");
				}
			}
		}

	}

}
